<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>控制台</title>
    <!-- 引入样式 -->
    <link href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/theme-chalk/index.min.css" rel="stylesheet">
    <style>
        body {
            font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;
        }
        a {
            text-decoration: none;
        }
        .el-menu-demo a {
            height: 60px;
        }
        .img {
            width: 80px;
            height: 80px;
            float: left;
            margin-right: 1em;
        }
    </style>
</head>
<body>
<div id="app">
    <el-container>
        <el-header>
            <el-menu default-active="1" class="el-menu-demo" mode="horizontal" :route="true">
                <el-menu-item index="1">管理中心</el-menu-item>
                <el-menu-item index="2"><a href="/user">用户管理</a></el-menu-item>
                <el-menu-item index="9" style="float: right;">
                    <span style="font-size: 14px; line-height: 3em; margin-right: 1em" :title="user.id">{{ user.username }}</span>
                    <el-button size="small" type="danger" @click="logout">退出</el-button>
                </el-menu-item>
            </el-menu>
        </el-header>
        <el-main>
            <el-form :inline="true" size="small">
                <el-dropdown type="danger" style="margin-right: .5em" @command="onHandleCommand">
                    <el-button type="danger" size="small">
                        批量操作<i class="el-icon-arrow-down el-icon--right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="publish">发布</el-dropdown-item>
                        <el-dropdown-item command="recall">撤回</el-dropdown-item>
                        <el-dropdown-item command="delete">删除</el-dropdown-item>
                        <el-dropdown-item command="recovery">恢复</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
                <el-button type="success" style="margin-right: .5em" size="small" @click="onCreate">新建</el-button>
                <el-form-item label="标题">
                    <el-input v-model="title" placeholder="请输入关键字"></el-input>
                </el-form-item>
                <el-form-item label="作者">
                    <el-select v-model="userId" placeholder="请选择">
                        <el-option v-for="item in options.users" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="发布状态">
                    <el-select v-model="isPublish" placeholder="请选择">
                        <el-option v-for="item in options.publish" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="删除状态">
                    <el-select v-model="isDelete" placeholder="请选择">
                        <el-option v-for="item in options.delete" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSearch">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="list" @selection-change="onHandleSelectionChange" style="width: 100%">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="封面" width="100">
                    <template slot-scope="scope">
                        <el-image class="img" :src="scope.row.cover" fit="cover"></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="新闻标题">
                    <template slot-scope="scope">
                        <el-link :href="scope.row.url" target="_blank" :disabled="!!scope.row.delete_time">{{ scope.row.title }}</el-link>
                        <p style="overflow:hidden; height: 3em">{{ scope.row.summary }}</p>
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="作者" width="120"></el-table-column>
                <el-table-column prop="publish_time" label="发布日期" width="180"></el-table-column>
                <el-table-column label="操作" width="240">
                    <template slot-scope="scope">
                        <div v-if="scope.row.user_id === user.id">
                            <el-button v-if="!scope.row.publish_time && !scope.row.delete_time" size="mini" type="primary" @click="onModify(scope.row)">编辑</el-button>
                            <el-button v-if="!scope.row.publish_time && !scope.row.delete_time" size="mini" type="success" @click="onPublish(scope.row)">发布</el-button>
                            <el-button v-else-if="scope.row.publish_time && !scope.row.delete_time" size="mini" type="warning" @click="onRecall(scope.row)">撤回</el-button>
                            <el-button v-if="!scope.row.publish_time && !scope.row.delete_time" size="mini" type="danger" @click="onDelete(scope.row)">删除</el-button>
                            <el-button v-else-if="scope.row.delete_time" size="mini" type="danger" @click="onRecovery(scope.row)">恢复</el-button>
                        </div>
                        <div v-else>
                            <el-link disabled>当前用户不可操作</el-link>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination style="text-align: center" layout="prev, pager, next" page-size="5" @current-change="handleCurrentChange" :total="count"></el-pagination>
        </el-main>
    </el-container>

    <el-dialog title="增改新闻" :visible.sync="dialogFormVisible">
        <el-form :model="news">
            <el-form-item label="新闻标题" :label-width="formLabelWidth">
                <el-input v-model="news.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="新闻简介" :label-width="formLabelWidth">
                <el-input v-model="news.summary" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="新闻链接" :label-width="formLabelWidth">
                <el-input v-model="news.url" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="新闻封面" :label-width="formLabelWidth">
                <el-upload class="upload-demo" action="" ref="uploadAvatar" :http-request="httpRequest" :headers="headers" :auto-upload="false" limit="1" list-type="picture-card">
                    <i slot="default" class="el-icon-plus"></i>
                </el-upload>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="onSubmit">提交</el-button>
        </div>
    </el-dialog>
</div>
</body>
<!-- 引入组件库 -->
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.9/vue.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
<script src="https://cdn.staticfile.org/store.js/2.0.12/store.legacy.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.14/index.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                user: {
                    id: 0,
                    username: '',
                    token: ''
                },
                title: '',
                userId: '',
                isPublish: '',
                isDelete: '',
                page: 1,
                list: [],
                total: 0,
                count: 0,
                headers: {
                    token: ''
                },
                ids: '',
                options: {
                    users: [],
                    publish: [
                        {label: '已发布', value: 1},
                        {label: '未发布', value: 0},
                    ],
                    delete: [
                        {label: '已删除', value: 1},
                        {label: '未删除', value: 0},
                    ],
                },
                dialogFormVisible: false,
                news: {
                    id: 0,
                    title: '',
                    summary: '',
                    url: '',
                    cover: '',
                },
                formLabelWidth: '120px'
            }
        },
        mounted() {
            this.user = store.get("user")
            this.headers.token = this.user.token
            this.getList()

            axios.get('/admin/news/users', {headers: this.headers}).then(res => res.data).then(res => {
                if (res.error) {
                    this.$alert(res.message)
                    return
                }

                this.options.users = res.data.list.map(item => { return { label: item.username, value: item.id } })
            });
        },
        methods: {
            getList() {
                let opt = [];
                if (this.title.length) {
                    opt.push(`title=${this.title}`);
                }
                if (parseInt(this.userId) > 0) {
                    opt.push(`userId=${this.userId}`);
                }
                if (typeof this.isPublish != "string") {
                    opt.push(`isPublish=${this.isPublish}`);
                }
                if (typeof this.isDelete != "string") {
                    opt.push(`isDelete=${this.isDelete}`);
                }

                const params = opt.length ? '&' + opt.join('&') : '';

                axios.get(`/admin/news/index?page=${this.page}&pageSize=5${params}`, {headers: this.headers}).then(res => res.data).then(res => {
                    if (res.error) {
                        this.$alert(res.message)
                        return
                    }

                    this.list = res.data.list
                    this.total = res.data.total
                    this.count = res.data.count
                })
            },
            handleCurrentChange(page) {
                this.page = page;
                this.getList();
            },
            onSearch() {
                this.page = 1;
                this.getList();
            },
            onPublish(item) {
                axios.post(`/admin/news/publish/${item.id}`, {}, {headers: this.headers}).then(res => res.data).then(res => {
                    if (res.error) {
                        this.$alert(res.message)
                        return
                    }

                    this.getList()
                })
            },
            onRecall(item) {
                axios.post(`/admin/news/recall/${item.id}`, {}, {headers: this.headers}).then(res => res.data).then(res => {
                    if (res.error) {
                        this.$alert(res.message)
                        return
                    }

                    this.getList()
                })
            },
            onDelete(item) {
                this.$confirm('确认删除文章吗？', '删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post(`/admin/news/delete/${item.id}`, {}, {headers: this.headers}).then(res => res.data).then(res => {
                        if (res.error) {
                            this.$alert(res.message)
                            return
                        }

                        this.$message({type: 'success', message: '删除成功!'});
                        this.getList()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '取消删除'
                    });
                });
            },
            onRecovery(item) {
                axios.post(`/admin/news/recovery/${item.id}`, {}, {headers: this.headers}).then(res => res.data).then(res => {
                    if (res.error) {
                        this.$alert(res.message)
                        return
                    }

                    this.getList()
                })
            },
            onHandleCommand(command) {
                this.$confirm('此操作将批量修改文章, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post(`/admin/news/batch`, { ids: this.ids, opt: command }, {headers: this.headers}).then(res => res.data).then(res => {
                        if (res.error) {
                            this.$alert(res.message)
                            return
                        }

                        this.$message({type: 'success', message: '操作成功'});
                        this.getList()
                    })
                }).catch(() => {
                    this.$message({type: 'info', message: '操作取消'});
                });
            },
            onHandleSelectionChange(items) {
                this.ids = items.map(val => parseInt(val.id)).join(',')
            },
            handleAvatarSuccess (res, file, fileList) {
                if (res.error) {
                    this.$alert(res.message)
                    return
                }

                this.news.cover = res.data.cover
            },
            httpRequest(e) {
                // 创建表单对象
                this.news.cover = e.file
            },
            onCreate() {
                this.news = { id: 0, title: '', summary: '', url: '', cover: '' };
                this.dialogFormVisible = true
            },
            onModify(row) {
                const { id, title, summary, url, cover } = { ...row }
                this.news = { id, title, summary, url, cover };
                this.dialogFormVisible = true
            },
            onSubmit() {
                this.$refs.uploadAvatar.submit();
                const url = parseInt(this.news.id) > 0 ? `/admin/news/modify/${this.news.id}` : `/admin/news/create`;
                axios.post(url, this.news, {headers: {'Content-Type': 'multipart/form-data', ...this.headers}}).then(res => res.data).then(res => {
                    if (res.error) {
                        this.$alert(res.message)
                        return
                    }

                    this.getList()
                    this.dialogFormVisible = false
                })
            },
            logout() {
                axios.get(`/auth/logout`, {headers: this.headers}).then(res => res.data).then(res => {
                    store.remove("user")
                    window.location.href = '/login'
                })
            }
        }
    })
</script>
</html>